package org.zj.springstyle.mvc.domain;

import org.zj.springstyle.mvc.parseJSON.NativatorBean;
import org.zj.springstyle.mvc.parseJSON.ParseJSON;
import org.zj.springstyle.mvc.parseXml.XMLBeans;
import org.zj.springstyle.mvc.util.parseXMLUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Map;

/**
 * Created by zhaoji on 14/12/24.
 */
public class ControllerListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext context = servletContextEvent.getServletContext();
        String tomcatpath = servletContextEvent.getServletContext().getRealPath("/");
        String isJSON = context.getInitParameter("isJSON");
        String isXML = context.getInitParameter("isXML");
        String xmlPath = "";
        String jsonPath = "";
            if((isJSON.equals("true") && isXML.equals("false"))
                    ||
                    (isJSON.equals("false") && isXML.equals("true"))){
                    if(isJSON.equals("true")){
                        jsonPath = context.getInitParameter("JSONnativator");
                        try {
                            Map<String,NativatorBean> map = ParseJSON.parseJSON(tomcatpath + jsonPath);
                            context.setAttribute("json",map);
                        }catch (Exception e){
                            System.out.println("APP地图装载异常：" + e.getMessage());
                        }
                    }else{
                        xmlPath = context.getInitParameter("XMLnativator");
                        try {
                            Map<String,XMLBeans> map = parseXMLUtil.parseStrutsXml(tomcatpath+xmlPath);
                            context.setAttribute("struts",map);
                        }catch (Exception e){
                            System.out.println("APP地图装载异常：" + e.getMessage());
                        }
                    }

                System.out.println("APP地图装载成功");
            }else {
                System.out.println("web.xml配置出现互斥异常！isJSON与isXML只能有一个为true或false");
            }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
